package com.dy.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dy.common.R;
import com.dy.common.RedisConstonts;
import com.dy.dto.DishDto;
import com.dy.entity.Dish;
import com.dy.entity.DishFlavor;
import com.dy.service.DishFlavorService;
import com.dy.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private StringRedisTemplate strRedis;

    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     * @Author dy
     * @Description:  新增保存菜品，和口味
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        return dishService.saveDishAndFlavor(dishDto);
    }

    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){

        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);
        //获取菜品总数
        Long total = dishService.getTotal(name);
        //查找菜品集合
        List<DishDto> list =  dishService.getDishList((page-1)*pageSize,pageSize,name);
        dishDtoPage.setRecords(list);
        dishDtoPage.setTotal(total);
        //返回数据
        return R.success(dishDtoPage);
    }


    /**
     * @Author dy
     * @Description: 根据ID 查询菜品
     */
    @GetMapping("/{id}")
    public R<DishDto> findById(@PathVariable Long id){
        return dishService.findById(id);
    }

    /**
     * @Author dy
     * @Description: 修改菜品 数据
     */
    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dishDto){
           return dishService.updateDish(dishDto);
    }

    /**
     * @Author dy
     * @Description: 修改菜品状态  0:停售 1：起售
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") Integer status,Long[] ids){
        List<Long> longs = Arrays.asList(ids);
        return dishService.updateStatus(status,longs);
    }

    /**
     * @Author dy
     * @Description: 删除菜品/ 对应口味
     */
    @DeleteMapping
    public R<String> deleteDish(Long[] ids){

        return dishService.deleteDish(ids);
    }

    /**
     * @Author dy
     * @Description: 获取菜品集合
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //查询Redis 看是否有缓存。           dish:915617651321_1   字符串+菜品分类ID+状态
        String s = strRedis.opsForValue().get(RedisConstonts.DISH_LIST + dish.getCategoryId() + "_" + dish.getStatus());
        //缓存命中，返回缓存数据
        if(StringUtils.isNotBlank(s)){
            log.info("缓存命中" + LocalDateTime.now());
            return R.success(JSONUtil.toList(s, DishDto.class));
        }
        //缓存未命中，缓存重建
        //添加过滤条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        // 分类条件
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        // 状态条件
        queryWrapper.eq(Dish::getStatus,1);
        //排序条件
        queryWrapper.orderByAsc(Dish::getSort);
        List<Dish> list = dishService.list(queryWrapper);

        //解决缓存穿透
        if(CollectionUtil.isEmpty(list)){
            log.info("缓存穿透");
            strRedis.opsForValue().set(
                    RedisConstonts.DISH_LIST + dish.getCategoryId() + "_" + dish.getStatus(),
                    "",
                    3, TimeUnit.MINUTES);
            return R.success(ListUtil.empty());
        }

        //给菜品添加对应口味
        List<DishDto>  dishDtos = list.stream().map(item ->{
            DishDto dishDto = new DishDto();
            //copy 元数据到DTO
            BeanUtil.copyProperties(item,dishDto);
            //添加 菜品ID 条件
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper();
            wrapper.eq(DishFlavor::getDishId,item.getId());
            List<DishFlavor> list1 = dishFlavorService.list(wrapper);
            if(!list1.isEmpty()){
                dishDto.setFlavors(list1);
            }
            return dishDto;
        }).collect(Collectors.toList());


        //将 从数据库查询到的数据存到redis
        String jsonStr = JSONUtil.toJsonStr(dishDtos);
        //加入缓存 过期时间 一小时
        log.info("缓存重建" + LocalDateTime.now());
        strRedis.opsForValue().set(
                RedisConstonts.DISH_LIST + dish.getCategoryId() + "_" + dish.getStatus(),
                jsonStr,
                1, TimeUnit.HOURS);
        //返回数据
        return R.success(dishDtos);
    }

}
